#!/bin/sh /etc/rc.common
# Copyright (c) 2014-2015 TP-LINK Technologies CO.,LTD.
# Copyright (c) 2013 Qualcomm Atheros, Inc.
# Copyright (C) 2006-2011 OpenWrt.org

START=05
RESUME=05

system_config() {
	local cfg="$1"

	local hostname conloglevel

	config_get hostname "$cfg" hostname 'SLP'
	echo "$hostname" > /proc/sys/kernel/hostname

	config_get conloglevel "$cfg" conloglevel
	config_get buffersize "$cfg" buffersize
	[ -z "$conloglevel" -a -z "$buffersize" ] || dmesg ${conloglevel:+-n $conloglevel} ${buffersize:+-s $buffersize}

	# config vm cache
	echo 1536 > /proc/sys/vm/min_free_kbytes
	echo 5 > /proc/sys/vm/dirty_ratio
}

# Set some defaults at the first time the device boots.
# This is a light version of 'uci-defaults'. by lizheng.
# NOTE:
# All scripts in the folder /etc/uci-defaults/ are automatically executed,
# and if they exited with code 0 deleted afterwards (scripts that did not
# exit with code 0 are not deleted and will be re-executed during the next
# boot until they also successfully exit).
# You can put your own default files in that folder.
apply_uci_config() {
	cd /etc/uci-defaults || return 0
	files="$(ls)"
	[ -z "$files" ] && return 0
	mkdir -p /tmp/.uci
	for file in $files; do
		( . "./$(basename $file)" )	# && rm -f "$file"
	done

	# Commit all sections here
	uci commit
}

start() {
	[ -f /proc/mounts ] || /sbin/mount_root
	[ -f /proc/jffs2_bbc ] && echo "S" > /proc/jffs2_bbc
	[ -f /proc/net/vlan/config ] && vconfig set_name_type DEV_PLUS_VID_NO_PAD

	mkdir -p /var/run
	mkdir -p /var/log
	mkdir -p /var/lock
	mkdir -p /tmp/usbdisk
	touch /var/log/wtmp
	touch /var/log/lastlog
	touch /tmp/resolv.conf.auto
	ln -sf /tmp/resolv.conf.auto /tmp/resolv.conf
	grep -q debugfs /proc/filesystems && mount -t debugfs debugfs /sys/kernel/debug

	load_modules /etc/modules.d/*

	apply_uci_config

	config_load system
	config_foreach system_config system

	# update timezone
	timezone.sh

	killall -q hotplug2
	[ -x /sbin/hotplug2 ] && /sbin/hotplug2 --override --persistent \
			--set-rules-file /etc/hotplug2.rules \
			--set-coldplug-cmd /sbin/udevtrigger \
			--max-children 1 >/dev/null 2>&1 &

	# create /dev/root if it doesn't exist
	[ -e /dev/root -o -h /dev/root ] || {
		rootdev=$(awk 'BEGIN { RS=" "; FS="="; } $1 == "root" { print $2 }' < /proc/cmdline)
		[ -n "$rootdev" ] && ln -s "$rootdev" /dev/root
	}
        
}

terminate() {
	kill -9 `pgrep hotplug2`
}

resume() {
	[ -x /sbin/hotplug2 ] && /sbin/hotplug2 --override --persistent \
			--set-rules-file /etc/hotplug2.rules \
			--set-coldplug-cmd /sbin/udevtrigger \
			--max-children 1 >/dev/null 2>&1 &
}
